package com.company.crm.workbench.service.impl;

import com.company.crm.commons.constants.Constants;
import com.company.crm.commons.util.DateUtils;
import com.company.crm.commons.util.UUIDUtils;
import com.company.crm.settings.domain.User;
import com.company.crm.workbench.domain.*;
import com.company.crm.workbench.mapper.*;
import com.company.crm.workbench.service.ClueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 作者：王磊栋
 * 2021/4/22
 */
@Service
public class ClueServiceImpl implements ClueService {
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private ContactsMapper contactsMapper;
    @Autowired
    private ClueRemarkMapper clueRemarkMapper;
    @Autowired
    private ContactsRemarkMapper contactsRemarkMapper;
    @Autowired
    private CustomerRemarkMapper customerRemarkMapper;
    @Autowired
    private ClueActivityRelationMapper clueActivityRelationMapper;
    @Autowired
    private ContactsActivityRelationMapper contactsActivityRelationMapper;
    @Autowired
    private TranMapper tranMapper;
    @Override
    public List<Clue> selectAllClue() {
        return clueMapper.selectAllClue();
    }

    @Override
    public Clue selectClueForDetailById(String id) {
        return clueMapper.selectClueForDetailById(id);
    }

    @Override
    public int insertClueByClue(Clue clue) {
        return clueMapper.insert(clue);
    }

    /*
      1、根据线索id获 取线索
         将线索 转换到 客户表信息和联系人表
      2、根据线索id获取 线索备注
         将线索备注表中的信息 转换到 客户备注表和联系人备注表
      3、根据线索id获取 线索活动关系
         线索和市场活动的关系 转换到 联系人和市场活动的关系
      4、如果在页面创建了交易，还需要创建一条交易历史。

      5、删除线索备注
      6、删除线索备注和市场活动的关系
      7、删除线索
      
     */
    @Override
    @Transactional( propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
    public int ConvertClue(Map<String, Object> map) {
        String clueId=(String)map.get("clueId");
        String isCreateTran=(String)map.get("isCreateTran");
        String amountOfMoney=(String)map.get("amountOfMoney");
        String tradeName=(String)map.get("tradeName");
        String expectedClosingDate=(String)map.get("expectedClosingDate");
        String stage=(String)map.get("stage");
        String activityId=(String)map.get("activityId");
        User user=(User) map.get(Constants.LOGIN_CODE_SUCCESS);

        //1、首先将线索转换到 客户表信息和联系人表
        Clue clue = clueMapper.selectClueById(clueId);
        Customer cus = new Customer();
        cus.setId(UUIDUtils.getUUID());
        cus.setOwner(clue.getOwner());
        cus.setName(clue.getCompany());
        cus.setWebsite(clue.getWebsite());
        cus.setPhone(clue.getPhone());
        cus.setCreateBy(user.getId());
        cus.setCreateTime(DateUtils.formatDateTime(new Date()));
        cus.setContactSummary(clue.getContactSummary());
        cus.setAddress(clue.getAddress());
        //插入一条客户
        int ret1 = customerMapper.insertCustomer(cus);
        if (ret1<=0){
            return -1;
        }
        Contacts con = new Contacts();
        con.setId(UUIDUtils.getUUID());
        con.setOwner(user.getId());
        con.setSource(clue.getSource());
        con.setCustomerId(cus.getId());
        con.setFullName(clue.getFullName());
        con.setAppellation(clue.getAppellation());
        con.setEditBy(clue.getEmail());
        con.setMphone(clue.getMphone());
        con.setJob(clue.getJob());
        con.setCreateBy(user.getId());
        con.setCreateTime(DateUtils.formatDateTime(new Date()));
        con.setDescription(clue.getDescription());
        con.setContactSummary(clue.getContactSummary());
        con.setNextContactTime(clue.getNextContactTime());
        con.setAddress(clue.getAddress());
        //插入一条联系人
        int ret2 = contactsMapper.insertContacts(con);
        if (ret2<=0){
            return -1;
        }
        //2、将线索备注表中的信息 转换到 客户备注表和联系人备注表
        List<ClueRemark> clueRemarkList = clueRemarkMapper.selectClueRemarkByClueId(clueId);
        if (clueRemarkList.size()>0){
            ClueRemark clueRemark = null;
            CustomerRemark customerRemark = null;
            ContactsRemark contactsRemark = null;
            List<CustomerRemark> customerRemarkList = new ArrayList<>();
            List<ContactsRemark> contactsRemarkList = new ArrayList<>();
            for (int i = 0; i < clueRemarkList.size(); i++) {
                clueRemark = clueRemarkList.get(i);
                customerRemark = new CustomerRemark();
                contactsRemark = new ContactsRemark();
                customerRemark.setId(UUIDUtils.getUUID());
                customerRemark.setNoteContent(clueRemark.getNoteContent());
                customerRemark.setCreateBy(user.getId());
                customerRemark.setCreateTime(DateUtils.formatDateTime(new Date()));
                customerRemark.setCustomerId(cus.getId());
                customerRemarkList.add(customerRemark);

                contactsRemark.setId(UUIDUtils.getUUID());
                contactsRemark.setNoteContent(clueRemark.getNoteContent());
                contactsRemark.setCreateBy(user.getId());
                contactsRemark.setCreateTime(DateUtils.formatDateTime(new Date()));
                contactsRemark.setContactsId(con.getId());
                contactsRemarkList.add(contactsRemark);
            }
            //根据集合插入 客户备注表 和 联系人备注表
            int ret3 = customerRemarkMapper.insertCustomerRemarkByList(customerRemarkList);
            if (ret3<=0){
                return -1;
            }
            int ret4 = contactsRemarkMapper.insertContactsRemarkByList(contactsRemarkList);
            if (ret4<=0){
                return -1;
            }
        }
        //3、线索和市场活动的关系 转换到 联系人和市场活动的关系
        //一个活动有多个线索（潜在客户）  主要是这个线索关系表来连接  一个（潜在客户）线索可以参加多个活动。
        List<ClueActivityRelation> clueActivityRelationList = clueActivityRelationMapper.selectClueActivityRelationByClueId(clueId);
        if (clueActivityRelationList.size()>0){
            //进行转化
            ClueActivityRelation clueActivityRelation = null;
            ContactsActivityRelation contactsActivityRelation = null;
            List<ContactsActivityRelation> contactsActivityRelationList = new ArrayList<>();
            for (int i = 0; i < clueActivityRelationList.size(); i++) {
                clueActivityRelation = clueActivityRelationList.get(i);
                contactsActivityRelation = new ContactsActivityRelation();
                contactsActivityRelation.setId(UUIDUtils.getUUID());
                contactsActivityRelation.setActivityId(activityId);
                contactsActivityRelation.setContactsId(con.getId());
                contactsActivityRelationList.add(contactsActivityRelation);
            }
            //插入
            int ret5 = contactsActivityRelationMapper.insertContactsActivityRelationByList(contactsActivityRelationList);
            if (ret5<=0){
                return -1;
            }
        }
        if("true".equals(isCreateTran)){
           Tran tran = new Tran();
           tran.setId(UUIDUtils.getUUID());
           tran.setOwner(user.getId());
           tran.setMoney(amountOfMoney);
           tran.setName(tradeName);
           tran.setExpectedDate(expectedClosingDate);
           tran.setStage(stage);
           tran.setContactsId(con.getId());
           tran.setActivityId(activityId);
           tran.setCreateBy(user.getId());
           tran.setCreateTime(DateUtils.formatDateTime(new Date()));
            //插入一条交易
            int ret6 = tranMapper.insertTran(tran);
            if (ret6<=0){
                return -1;
            }
        }
       /* 5、删除线索备注
        6、删除线索备注和市场活动的关系
        7、删除线索*/
        int result = clueRemarkMapper.deleteClueRemarkByClueId(clueId);
        clueActivityRelationMapper.deleteClueActivityRelationByClueId(clueId);
        clueMapper.deleteClueById(clueId);
        return 1;
    }
}
